package cc.ufinity.networkdiagnose.util;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.util.Log;

public class GPSUtils {
	private Context ctx;
	private LocationManager locationManager;
	private String provider;
	private Location location;

	public GPSUtils(Context ctx) {
		this.ctx = ctx;
		init();
	}

	public Location getLocation() {
		return location;
	}

	private void init() {
		try {
			locationManager = (LocationManager)ctx	.getSystemService(Context.LOCATION_SERVICE);		
			ContentResolver cr = ctx.getContentResolver(); 
			if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || !locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER))
			{                           
				Secure.setLocationProviderEnabled(cr, LocationManager.GPS_PROVIDER, true);
				Secure.setLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER, true);
				locationManager = (LocationManager)ctx	.getSystemService(Context.LOCATION_SERVICE);	
			}
		
//			 openGps();
			setProvider();
			if(provider != null)
				this.location = locationManager.getLastKnownLocation(provider); 
		} catch (Exception e) {
				// TODO: handle exception
		}
	}

	public Double getLatitude() {
//		return (location != null) ? (location.getLatitude() * 1E6) : 0;
		return (location != null) ? (location.getLatitude()) : 0;

	}

	public Double getLongitude() {
//		return (location != null) ? (location.getLongitude() * 1E6) : 0;  
		return (location != null) ? (location.getLongitude()) : 0;
	}

	@Deprecated
	private void openGps() {

		if (!locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

			// 如果GPS不可用，则跳转到Settings中进行设置
			Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			ctx.startActivity(intent);
		}
	}

	private void setProvider() {

		// 构建位置查询条件
		Criteria criteria = new Criteria();

		// 查询精度：高
		criteria.setAccuracy(Criteria.ACCURACY_FINE);

		// 是否查询海拨：否
		criteria.setAltitudeRequired(false);

		// 是否查询方位角 : 否
		criteria.setBearingRequired(false);

		// 是否允许付费：是
		criteria.setCostAllowed(false);

		// 电量要求：低
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		// 返回最合适的符合条件的 provider，第 2个参数为 true说明 如果只有一个 provider 是有效的 ,
		// 则返回当前provider
		provider = locationManager.getBestProvider(criteria, true);
	    Log.e("GPS", "provider = " + provider);
	}
}
